<?php
/**
 * @package PHPKit.
 * @author: mawenpei
 * @date: 2016/12/2
 * @time: 9:27
 */
namespace HuoKit\HuoServer\Core;

use swoole_process as SwooleProcess;

abstract class Process
{
    public $name;

    public $process;

    public $params;

    public $logger;

    public function init(SwooleProcess $worker)
    {
        static::run();
        $self = $this;
        swoole_event_add($worker->pipe,function($pipe)use($self){
            $worker = $self->process;
            $result = $worker->read();
            $command = $self->runCommand($result);
            $worker->write($command);
        });
    }

    public function runCommand($result = '')
    {
        $info = null;
        $data = null;
        $command = null;

        if (!empty($result)) {
            $command = unserialize($result);
            $commandAction = $command->getCommand();
            $data = $command->getData();
        }

        $action = 'command' . ucfirst($commandAction);
        if (method_exists($this, $action)) {
            $info = $this->{$action}($data);
            $command->setResult($info);
        } else {
            $this->logger && $this->logger->error("command {$action} is error!");
        }

        return $command;
    }

    /**
     * 向主进程发送数据
     * @param $data
     */
    public function sendMaster($data = '')
    {
        return $this->process->write($data);
    }

    abstract public function run();

    /**
     * 当前work状态
     */
    abstract function commandStatus();
}